package com.dianrui.moonfire.walkbaby;

import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.SPUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.activity.BaseActivity;
import com.dianrui.moonfire.alipay.PayResult;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:遛娃付押金
 * User: lzy
 * Date: 2020-8-17
 */

public class WalkBabyDespoitActivity extends BaseActivity {
    private String vehicleStatus;
    private String vehicleIds, devicenumbers, isRomotes;
    private Double lat;
    private Double lng;
    private BleDevice bleDevices;
    private BluetoothAdapter blueadapter;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.cb_zfb)
    CheckBox cbZfb;
    @BindView(R.id.cb_wx)
    CheckBox cbWx;

    @Override
    public int getContentViewId() {
        return R.layout.activity_walkbaby_despoit;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(true);
        title.setText(getString(R.string.walkbabydeponsit_titles));
        blueadapter = BluetoothAdapter.getDefaultAdapter();
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                devicenumbers = bundle.getString("number");

            }
        }
        getInfoPrice();

    }

    @Override
    public void initData() {}

    @OnClick({R.id.back, R.id.cb_zfb, R.id.click_zfb, R.id.cb_wx, R.id.click_wx, R.id.click_yes})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.click_zfb:
                changeType(2);
                break;
            case R.id.cb_zfb:
                changeType(2);
                break;
            case R.id.cb_wx:
                changeType(1);
                break;
            case R.id.click_wx:
                changeType(1);
                break;
            case R.id.click_yes:
                if (cbWx.isChecked()) {
                    wxPays(money.getText().toString());
                } else if (cbZfb.isChecked()) {
                    alipays(money.getText().toString());
                }
                break;
            default:
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String str) {
        if (TextUtils.equals(str, EventBusConstants.LWPAYSUCEESS)) {
            JumpActivitys(WalkBabyTipsActivity.class);
            finish();
        }
    }


    private void getInfoPrice() {
        JsonObject Json = new JsonObject();
        Json.addProperty("number", devicenumbers);
        Json.addProperty("is_remote", "1");
        Json.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        XHttpRequest.getInstance().postRequests(Url.BABYRULE, Json.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        if (isFinishing()) {
                            return;
                        }
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                String data = JsonUtils.getJsonStr(response, "data");
                                money.setText(JsonUtils.getJsonStr(data, "deposit"));
                                vehicleIds = JsonUtils.getJsonStr(data, "vehicle_id");
                                showRuleDialog(JsonUtils.getJsonStr(data, "instruction"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void showRuleDialog(String instruction) {
        AlertDialog.Builder builder = new AlertDialog.Builder(WalkBabyDespoitActivity.this, R.style.RcDialogs);
        final View view1 = LayoutInflater.from(WalkBabyDespoitActivity.this).inflate(R.layout.walkbaby_doposit_rule, null);
        final TextView content = view1.findViewById(R.id.content);
        content.setText(instruction);
        Button know=view1.findViewById(R.id.know);

        final AlertDialog dialog = builder.create();
        dialog.setView(view1);
        dialog.show();
        know.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }


    private void changeType(int what) {
        String type;
        if (1 == what) {
            cbWx.setChecked(true);
            cbZfb.setChecked(false);
        } else {
            cbWx.setChecked(false);
            cbZfb.setChecked(true);
        }

    }

    private void wxPays(String moneys) {
        showLoadingDialog(getString(R.string.paying));
        JsonObject pay = new JsonObject();
        pay.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        pay.addProperty("payment_mode", "2");//支付方式（必传）2微信，3支付宝，5微信小程序，6支付宝小程序支付
        pay.addProperty("number", money.getText().toString());
        pay.addProperty("ids", vehicleIds);
        XHttpRequest.getInstance().postRequests(Url.BABYPAY, pay.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                IWXAPI msgApi = WXAPIFactory.createWXAPI(WalkBabyDespoitActivity.this, Constant.WXAppID, true);
                                if (!msgApi.isWXAppInstalled()) {
                                    ToastUtil.showToast(getString(R.string.wx_installed));
                                }
                                PayReq payReq = new PayReq();
                                payReq.appId = jsonObject.getJSONObject("data").getString("appid");
                                payReq.partnerId = jsonObject.getJSONObject("data").getString("partnerid");
                                payReq.prepayId = jsonObject.getJSONObject("data").getString("prepayid");
                                payReq.packageValue = jsonObject.getJSONObject("data").getString("package");
                                payReq.nonceStr = jsonObject.getJSONObject("data").getString("noncestr");
                                payReq.timeStamp = jsonObject.getJSONObject("data").getString("timestamp");
                                payReq.extData = "WalkBaby";
                                payReq.sign = jsonObject.getJSONObject("data").getString("sign");
                                msgApi.sendReq(payReq);

                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void alipays(String moneys) {
        showLoadingDialog(getString(R.string.paying));
        JsonObject pay = new JsonObject();
        pay.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        pay.addProperty("payment_mode", "3");//支付方式（必传）2微信，3支付宝，5微信小程序，6支付宝小程序支付
        pay.addProperty("number", money.getText().toString());
        pay.addProperty("ids", vehicleIds);
        XHttpRequest.getInstance().postRequests(Url.BABYPAY, pay.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                if (!MyUtil.checkAliPayInstalled(WalkBabyDespoitActivity.this)) {
                                    ToastUtil.showToast(getString(R.string.zfb_installed));
                                }
                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            PayTask alipay = new PayTask(WalkBabyDespoitActivity.this);
                                            final Map<String, String> res = alipay.payV2(jsonObject.optJSONObject("data").getString("contents"), true);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    PayResult payResult = new PayResult(res);
                                                    String resultInfo = payResult.getResult();
                                                    String resultStatus = payResult.getResultStatus();
                                                    if ("9000".equals(resultStatus)) {
                                                        ToastUtil.showToast(getString(R.string.pay_success));
                                                        JumpActivitys(WalkBabyTipsActivity.class);
                                                        finish();
                                                    } else {
                                                        ToastUtil.showToast(getString(R.string.pay_failed));
                                                    }
                                                }
                                            });
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                };

                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
